<template>
  <div class="chat-detail-container">
    <div class="chat-history">
      <div
        v-for="(msg, index) in messages"
        :key="index"
        class="message-item"
        :class="{ self: msg.sender_id === userId - 999999 }"
      >
        <div class="message-content">
          <span class="content">{{ msg.content }}</span>
          <div class="timestamp">{{ msg.timestamp }}</div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <el-input
        v-model="newMessage"
        placeholder="输入消息..."
        @keyup.enter="localSendMessage"
      />
      <el-button type="primary" @click="localSendMessage">发送</el-button>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  onMounted,
  onBeforeUnmount,
  defineEmits,
  nextTick,
} from "vue";
import {
  connectDetailWebSocket,
  sendDetailMessage,
  closeDetailWebSocket,
} from "@/utils/websocket";

const props = defineProps({ chatId: Number });
const emit = defineEmits(["newMessage"]);

const userId = 1000000;
const receiverId = ref(props.chatId);
const messages = ref([]);
const newMessage = ref("");

// 接收到新消息的处理
const handleReceiveDetailMessage = (msg) => {
  const formattedTime = msg.timestamp
    ? new Date(msg.timestamp).toLocaleString()
    : "无时间";
  const messageData = {
    sender_id: msg.sender_id,
    content: msg.content,
    timestamp: formattedTime,
  };

  messages.value.push(messageData);
  emit("newMessage", messageData);
  scrollToBottom();
};

const scrollToBottom = () => {
  nextTick(() => {
    const chatHistory = document.querySelector(".chat-history");
    if (chatHistory) {
      chatHistory.scrollTo({
        top: chatHistory.scrollHeight,
        behavior: "smooth",
      });
    }
  });
};

// 发送消息
const localSendMessage = () => {
  if (newMessage.value.trim()) {
    const msg = {
      sender_id: userId,
      content: newMessage.value.trim(),
      timestamp: Date.now(),
    };
    sendDetailMessage(JSON.stringify(msg));
    messages.value.push({
      ...msg,
      sender_id: userId - 999999,
      timestamp: new Date(msg.timestamp).toLocaleString(),
    });
    newMessage.value = "";
  }
  scrollToBottom();
};

const establishDetailWebSocketConnection = () => {
  closeDetailWebSocket();
  connectDetailWebSocket(userId, receiverId.value, handleReceiveDetailMessage);
};

onMounted(() => {
  establishDetailWebSocketConnection();
});

watch(
  () => props.chatId,
  (newChatId) => {
    messages.value = [];
    receiverId.value = newChatId;
    establishDetailWebSocketConnection();
  }
);

onBeforeUnmount(() => {
  closeDetailWebSocket();
});
</script>

<style scoped>
.chat-detail-container {
  display: flex;
  flex-direction: column;
  max-inline-size: 72vh;
  min-height: 94%;
  min-width: 96%;
  padding: 16px;
  background-color: #f4f6f8;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  max-height:94% ;
}

.chat-history {
  flex-grow: 1;
  overflow-y: auto;
  height: 100%;
  padding: 10px 15px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
}

.message-item {
  display: flex;
  justify-content: flex-start;
  margin: 10px 0;
}

.message-item.self {
  justify-content: flex-end;
}

.message-content {
  display: inline-flex;
  flex-direction: column;
  padding: 10px 15px;
  border-radius: 18px;
  max-width: 60%;
  background: #f1f5f9;
  color: #333;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
  transition: background-color 0.2s ease, transform 0.2s ease;
}

.message-item.self .message-content {
  background: #4f3cc9;
  color: #ffffff;
  transform: scale(1.02);
}

.message-content:hover {
  transform: scale(1.02);
  background-color: #e6ecf1;
}

.message-item.self .message-content:hover {
  background: #3e2eb0;
}

.content {
  display: inline-block;
  word-wrap: break-word;
  font-size: 1rem;
  line-height: 1.5;
}

.timestamp {
  font-size: 0.75rem;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.chat-input {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
}

.chat-history::-webkit-scrollbar {
  width: 8px;
}

.chat-history::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.chat-history::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  border-radius: 4px;
}
</style>
